<?php

class Value {
    private $_table;
    private $_fields;
    private $_primary;
    private $_dao;

    public function setTable($table) {
        $this->_table = $table;
    }
    public function setFields($fields) {
        $this->_fields = $fields;
    }
    public function setPrimary($primary) {
        $this->_primary = $primary;
    }

    public function setDao($dao) {
        $this->_dao = $dao;
    }

    public function remove() {
        $primaryValue = $this->{$this->_primary};

        $sql = "delete from {$this->_table} where {$this->_primary}= ?";

        $result = $this->_dao->exec($sql, array($primaryValue));
        
        return $result;
    }

    public function save() {

        $primaryValue = $this->{$this->_primary};

        if ($primaryValue) {
            $sql = "select count(1) from {$this->_table} where {$this->_primary} = ?";

            $rowCount = $this->_dao->getRowCount($sql, array($primaryValue));

            if ($rowCount > 0) {
                return $this->_update();
            }
        }
        return $this->_insert();
    }

    private function _update() {
        $fieldArray = $this->_fields;
        $fieldSetArray = array();
        $binds = array();
        $sql = "update {$this->_table} set ";
        $i = 0;
        foreach ($fieldArray as $key=>$fieldName) {
            if (($this->{$fieldName} === null) || ($fieldName == $this->_primary)) {
                unset($fieldArray[$key]);
                continue;
            }
            if($i>0){
                $sql .= ', ';
            }
            $sql .=   " {$fieldName}= ? ";
            $binds[] = $this->{$fieldName};
            $i++;
        }
        $binds[] = $this->{$this->_primary};
        $sql .=  " where {$this->_primary} = ? limit 1";
        $result = $this->_dao->exec($sql, $binds);
        return $result;
    }

    private function _insert() {
        $fieldArray = $this->_fields;
        $valueArray = array();
        $binds = array();
        foreach ($fieldArray as $key=>$fieldName) {
            if (($this->$fieldName === null) || ($fieldName == $this->_primary)) {
                unset($fieldArray[$key]);
                continue;
            }
            $valueArray[$key] = ":$fieldName";
            $binds[":$fieldName"] = $this->{$fieldName};
        }

        $fieldString = implode(',', $fieldArray);
        $valueString = implode(',', $valueArray);
        $sql = "insert into {$this->_table} ($fieldString) values ($valueString)";
        $result = $this->_dao->exec($sql, $binds); 
        
        $primaryValue = $this->_dao->lastInsertId();

        $this->{$this->_primary} = $primaryValue;
        return $primaryValue;
    }
}
